<!-- 商机 -->
<template>
  <view>
    <!-- <u-navbar
      title=""
      :leftIconSize="state.leftIconSize"
      :placeholder="true"
      :autoBack="true"
    >
    </u-navbar> -->
    <view class="header-bg">
      <u-swiper
        :list="listBanner"
        keyName="image"
        showTitle
        :autoplay="true"
        :interval="3000"
        :duration="500"
        :height="state.swiperHeight + 'px'"
        imgMode="aspectFit"
        circular
        @click="clickWwiper"
      ></u-swiper>
    </view>
    <view class="search-bar">
      <u-search
        v-model="formData.project_name"
        placeholder="搜索需求（项目名称）"
        @search="clickSearch"
        @custom="clickSearch"
        @clear="handleClear"
        shape="round"
        bg-color="#f5f5f5"
        margin="15rpx"
      ></u-search>
    </view>
    <u-tabs :list="tabsList" @click="tabsClick" :scrollable="false"> </u-tabs>

    <view>
      <scroll-view
        class="function-scroll"
        scroll-y
        @scrolltolower="buttonScrolltolower"
        show-scrollbar="false"
        :scroll-with-animation="true"
        :style="{ height: 'calc(100vh - 45vh)' }"
      >
        <u-empty
          mode="data"
          text="暂无数据"
          v-if="dataList.length == 0"
          marginTop="20%"
          :icon="getResource('img/phone/mini/no_data.png')"
        />
        <view v-else>
          <view class="tab-panel">
            <view
              class="tab-panel-item"
              :class="{ 'tab-active': true }"
              v-for="(item, index) in dataList"
              :key="index"
              @click="handleItemClick(item)"
            >
              <view class="card-container">
                <!-- 标题和标签区域 -->
                <view class="header-section">
                  <view class="title">{{ item.need_title }}</view>
                  <view class="tags">
                    <u-tag
                      :text="item.project_jia_ji == 2 ? '加急中' : '不加急'"
                      :type="item.project_jia_ji == 2 ? 'error' : 'info'"
                      size="mini"
                      shape="circle"
                    />
                    <u-tag
                      v-if="item.status_note"
                      text="有备注"
                      type="warning"
                      size="mini"
                      shape="circle"
                    />
                  </view>
                </view>

                <!-- 主要内容区域 -->
                <view class="content-section">
                  <!-- 基本信息行 -->
                  <view class="info-row">
                    <u-icon name="map" size="14" color="#7a7a7a"></u-icon>
                    <text class="info-text location"
                      >项目地点：{{ item.need_city_name || "未填写" }}</text
                    >
                  </view>

                  <view class="info-row">
                    <u-icon name="tags" size="14" color="#7a7a7a"></u-icon>
                    <text class="info-text type"
                      >项目类型：{{ item.company_type_name }}需求</text
                    >
                  </view>
                  <!-- 时间信息行 - 使用特殊样式 -->
                  <view
                    style="
                      display: flex;
                      justify-content: space-between;
                      background-color: #f9f9f9;
                      align-items: center;
                    "
                  >
                    <view class="time-info-group">
                      <view class="time-info-row">
                        <u-icon
                          name="calendar"
                          size="14"
                          color="#7a7a7a"
                        ></u-icon>
                        <text class="time-text">发布时间：</text>
                        <text class="time-value">{{
                          item.publish_time_show || "---"
                        }}</text>
                      </view>

                      <view class="time-info-row">
                        <u-icon name="clock" size="14" color="#7a7a7a"></u-icon>
                        <text class="time-text">截止时间：</text>
                        <text class="time-value urgent">{{
                          item.need_ent_date || "---"
                        }}</text>
                      </view>
                    </view>
                    <view
                      style="font-size: 28rpx; margin-right: 15rpx"
                      v-if="Number(item.left_day) > 0"
                    >
                      距离结束<span
                        style="
                          color: red;
                          font-size: 40rpx;
                          border: 2px solid red;
                          border-radius: 50%;
                          padding: 15px;
                          margin: 0 5px;
                          display: inline-flex;
                          justify-content: center;
                          align-items: center;
                          width: 60rpx;
                          height: 60rpx;
                          box-sizing: border-box;
                        "
                        >{{ item.left_day }} </span
                      >天
                    </view>
                  </view>

                  <!-- 备注信息 -->
                  <view class="info-row" v-if="item.status_note">
                    <u-icon name="edit-pen" size="14" color="#7a7a7a"></u-icon>
                    <text class="info-text note"
                      >审核备注：{{ item.status_note }}</text
                    >
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <cardPopup v-model="state.on_of" />
    <u-modal
      :show="state.modalOn_of"
      title="系统消息"
      :showCancelButton="true"
      confirmText="立即充值"
      cancelText="立即购买"
      @cancel="modalCancel(1)"
      @confirm="modalCancel(2)"
    >
      <view class="slot-content"> 您当前余额不足,立刻充值有优惠 </view>
    </u-modal>
    <view>
      <Tabbar :index="2"></Tabbar>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed, toRefs } from "vue";
import {
  showToast,
  showLoading,
  hideLoading,
  showModalNoCancel,
  showModal,
} from "@/utils/toast";
import { getResource } from "../../../utils/Resource";
import { gatList, getStage, getNeedList } from "../../../api/demand.js";
import { PostNeed_id } from "../../../api/news.js";
import { onShow, onLoad } from "@dcloudio/uni-app";
import { getBanner } from "@/api/userInfo.js";
// 状态管理
const state = reactive({
  leftIconSize: 0,
  swiperHeight: "",
  on_of: false,
  modalOn_of: false,
  sidebarIndex: 0,
  listBanner: [],
  dataList: [],
  tabsList: [
    {
      id: "1",
      name: "公海",
    },
    {
      id: "2",
      name: "已购买",
    },
    {
      id: "3",
      name: "已完结",
    },
  ],
  count: 0,
  formData: {
    project_name: "",
    status: "",
    page_no: 1,
    page_size: 10,
    page_count: 1,
  },
});
const { formData, dataList, tabsList, listBanner } = toRefs(state);

onLoad(async (e) => {
  try {
    // 在onLoad中动态计算（示例）
    const systemInfo = uni.getSystemInfoSync();
    const screenWidth = systemInfo.windowWidth;
    state.swiperHeight = screenWidth * 0.4875; // 按比例计算高度
    const res = await getBanner("6");
    console.log(res);
    // list.value.banner = res.data;
    listBanner.value = res.data.map((item) => ({
      // 轮播图图片地址（根据接口返回的cover字段拼接完整URL）
      image: item.img_show,
      id: item.id,
      title: item.title,
      url: `/pages_index/news/component/detail?id=${item.id}`,
      type: "image",
    }));
    console.log(list.value.banner);
  } catch (error) {}
  console.log(e.type);
  if (e.type) {
    state.leftIconSize = 20;
  }
  await tabsClick(tabsList.value[0]);
});
const init = async () => {
  try {
    showLoading("加载中...");
    const res = await getNeedList(formData.value);
    console.log(res);
    const { count, page_count, page_no, page_size, list } = res.data;
    dataList.value = [...dataList.value, ...list];
    state.count = count;
    Object.assign(formData.value, {
      page_count,
      page_no,
      page_size,
    });
  } catch (error) {}
};

const tabsClick = async (e) => {
  formData.value.page_no = 1;
  dataList.value = [];
  formData.value.status = e.id;
  await init();
};
// 搜索处理
const clickSearch = async () => {
  if (!formData.value.project_name) {
    showToast("请输入项目名称关键词");
    return;
  }
  formData.value.page_no = 1;
  dataList.value = [];
  await init();
};

// 清空搜索
const handleClear = async () => {
  formData.value.project_name = "";
  formData.value.page_no = 1;
  dataList.value = [];
  await init();
};

// 点击列表项（跳转详情页）
const zhiFuShuJu = ref();
const modalCancel = (e) => {
  // console.log(e);
  state.modalOn_of = false;
  if (e == 1) {
    uni.requestPayment({
      provider: "wxpay",
      timeStamp: zhiFuShuJu.value.timestamp,
      nonceStr: zhiFuShuJu.value.nonceStr,
      package: zhiFuShuJu.value.package,
      signType: "MD5",
      paySign: zhiFuShuJu.value.paySign,
      success: function (res) {
        if (res.code == 10000) {
          init();
          uni.showToast({
            title: "充值成功",
            //将值设置为 success 或者直接不用写icon这个参数
            icon: "success",
            //显示持续时间为 2秒
            duration: 2000,
          });
        }
      },
      fail: function (err) {
        uni.showToast({
          title: "充值失败请联系管理员",
          //将值设置为 success 或者直接不用写icon这个参数
          icon: "error",
          //显示持续时间为 2秒
          duration: 2000,
        });
        console.log("fail:" + JSON.stringify(err));
      },
    });
  } else {
    state.on_of = true;
  }
};
const handleItemClick = async (e) => {
  uni.navigateTo({
    url: `/pages/user/component/recruitList?id=${e.id}`,
  });
  // console.log(e.pay_amount);
  // try {
  //   const res = await getLoginInfo();
  //   console.log(res.data.balance);
  //   if (e.pay_status == 1) {
  //     showModal(
  //       {
  //         title: "系统消息",
  //         content: `购买本条信息需要花费${e.pay_amount}元，您当前的余额为${res.data.balance}`,
  //       },
  //       (result) => {
  //         if (result.confirm) {
  //           const userinfo = uni.getStorageSync("userinfo");
  //           setTimeout(() => {
  //             PostNeed_id(e.id).then((res) => {
  //               // console.log(res.data);

  //               if (res.data == "1") {
  //                 dataList.value = [];
  //                 // showToast("购买成功");
  //                 init();
  //                 showModal(
  //                   {
  //                     title: "系统消息",
  //                     content: "您的已购买",
  //                     showCancel: false,
  //                   },
  //                   (result) => {}
  //                 );
  //                 return;
  //               }
  //               state.modalOn_of = true;
  //               zhiFuShuJu.value = res.data;
  //             });
  //           }, 500);
  //         } else {
  //           // 取消
  //         }
  //       }
  //     );
  //     return;
  //   }
  //   uni.navigateTo({
  //     url: `/pages/user/component/recruitList?id=${e.id}`,
  //   });
  // } catch (error) {}
};

const xiuGai = (e) => {
  if (e.status == 1 || e.status == 3) {
    if (e.company_type == "2") {
      uni.navigateTo({
        url: `/pages_index/demand/component/project?id=${e.id}&type=2`,
      });
    }
    if (e.company_type == "5") {
      uni.navigateTo({
        url: `/pages_index/demand/component/supervisorForm?id=${e.id}&type=2`,
      });
    }
    if (e.company_type == "6") {
      uni.navigateTo({
        url: `/pages_index/demand/component/dataForm?id=${e.id}&type=2`,
      });
    }
    if (e.company_type == "4") {
      uni.navigateTo({
        url: `/pages_index/demand/component/designForm?id=${e.id}&type=3`,
      });
      return;
    }
  }
};

const buttonScrolltolower = async () => {
  if (state.count != dataList.value.length) {
    formData.value.page_no++;
    showLoading("加载中");
    await init();
  } else {
    showToast("已经最后一页了~");
  }
};
</script>

<style lang="scss" scoped>
.search-container {
  padding: 12rpx 16px;
  background: #f8f8f8;
  border-radius: 8px;
  margin: 10rpx;
}

.custom-search {
  --u-search-input-background: #fff;
  --u-search-input-border-radius: 24px;
  /* 更大的圆角 */
  --u-search-input-height: 44px;
  --u-search-input-padding: 0 16px;
  --u-search-input-border: 1px solid #e0e0e0;
}

.search-button {
  background: #137ad3;
  color: white;
  border: none;
  border-radius: 20px;
  padding: 5px 16px;
  height: 36px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-left: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-button:hover {
  background: #40a9ff;
  transform: translateY(-1px);
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
}

.search-button:active {
  background: #096dd9;
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.tab-panel {
  padding: 12rpx;
}

.tab-panel-item {
  margin-bottom: 24rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  background-color: #fff;
  border: 1rpx solid #f0f0f0;

  &:active {
    transform: scale(0.98);
    opacity: 0.9;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.12);
  }
}

.card-container {
  padding: 28rpx;
}

/* 标题区域样式 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24rpx;

  .title {
    font-size: 34rpx;
    font-weight: 600;
    color: #222;
    flex: 1;
    margin-right: 20rpx;
    line-height: 1.4;
    letter-spacing: 0.5rpx;
    word-break: break-word;
  }

  .tags {
    display: flex;
    flex-wrap: wrap;
    gap: 10rpx;
    align-items: center;
  }
}

/* 内容区域样式 */
.content-section {
  .info-row {
    display: flex;
    align-items: center;
    margin-bottom: 18rpx;

    .info-text {
      margin-left: 10rpx;
      font-size: 28rpx;
      line-height: 1.5;

      &.location {
        color: #4a6baf;
      }

      &.type {
        color: #5e8b5e;
      }

      &.note {
        color: #b85c5c;
        font-size: 26rpx;
      }
    }
  }

  /* 时间信息组样式 */
  .time-info-group {
    background-color: #f9f9f9;
    border-radius: 12rpx;
    padding: 16rpx;
    margin: 20rpx 0;

    .time-info-row {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .time-text {
        font-size: 22rpx;
        color: #666;
        margin-left: 8rpx;
      }

      .time-value {
        font-size: 22rpx;
        color: #333;
        margin-left: 6rpx;
        font-weight: 500;

        &.urgent {
          color: #e74c3c;
          font-weight: 600;
        }
      }
    }
  }
}

/* 标签样式增强 */
.u-tag {
  margin-left: 0 !important;

  &.u-type-error {
    font-weight: bold;
    background-color: #ffecec !important;
    color: #e74c3c !important;
  }

  &.u-type-warning {
    font-weight: bold;
    background-color: #fff8e6 !important;
    color: #f39c12 !important;
  }

  &.u-type-info {
    background-color: #f0f7ff !important;
    color: #3498db !important;
  }
}

/* 响应式调整 */
@media (max-width: 360px) {
  .header-section .title {
    font-size: 30rpx;
  }

  .content-section {
    .info-text {
      font-size: 26rpx;

      &.note {
        font-size: 24rpx;
      }
    }

    .time-info-group {
      .time-text,
      .time-value {
        font-size: 24rpx;
      }
    }
  }
}
</style>
